﻿using System;
using System.Windows.Forms;
using Relocation.UI;
using log4net;
using Relocation.Base;
using Relocation.Service;
using Relocation.Data;
using System.Diagnostics;

namespace Relocation
{
	static class Program
	{
		/// <summary>
		/// 应用程序的主入口点。
		/// </summary>
		[STAThread]
		static void Main()
		{
			log4net.ILog _Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
			try
			{
				Application.EnableVisualStyles();
				Application.SetCompatibleTextRenderingDefault(false);
				
				if (CheckUpdate(_Log))
					return;		//自动更新
				Session session = GetSession();		//初始化Session
				session.User = GetUser(session);	//登录
				if (session.User == null)
					return;

				MainWindow mw = new MainWindow(session);
				session.Map.Add(Session.KEY_MAIN_WINDOW, mw);
				Application.Run(mw);
				Debug.WriteLine("程序结束！");

			} catch (Exception ex)
			{
				_Log.Error(ex.InnerException != null ? ex.InnerException.Message : ex.Message);
				Relocation.Com.MyMessagebox.Error("系统错误！");
			}
		}

		/// <summary>
		/// 自动更新
		/// </summary>
		/// <returns>是否需要重启程序</returns>
		static bool CheckUpdate(ILog log)
		{
			bool needRestar = false;
			try
			{
				Updater.Updater update = new Updater.Updater();
				needRestar = update.Update();
			} catch (Exception ex)
			{
				log.Error(ex.Message);
				needRestar = false;
			}
			return needRestar;

		}

		/// <summary>
		/// 初始化Session 
		/// </summary>
		/// <returns></returns>
		static Session GetSession()
		{
			Session session = new Session();
			session.DataRefresh = true;
			session.DataModel = new DataModel();			
			return session;
		}

		/// <summary>
		/// 登录，返回登录的用户
		/// </summary>
		/// <param name="session"></param>
		/// <returns>登录用户</returns>
		static User GetUser(Session session)
		{
			try
			{
				LoginForm login = new LoginForm(session);
				login.ShowDialog();
				return login.User;
			} catch (Exception)
			{
				throw;
			}
		}
	}
}
